<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="bom编码" prop="bomCode">
        <el-input
          v-model="queryParams.bomCode"
          placeholder="请输入bom编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mes:BOM:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['mes:BOM:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['mes:BOM:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['mes:BOM:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="BOMList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="bom编码" align="center" prop="bomCode" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="产品编码" align="center" prop="productCode" />
      <!-- <el-table-column label="物料id" align="center" prop="materialId" /> -->
      <!-- <el-table-column label="物料名称" align="center" prop="materialName" />
      <el-table-column label="物料数量" align="center" prop="materialNum" /> -->
      <!-- <el-table-column label="物料类型" align="center" prop="materialType" /> -->
      <el-table-column label="备注" align="center" prop="note" />
      <el-table-column label="创建人" align="center" prop="userId" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mes:BOM:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['mes:BOM:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改BOM管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="产品名称:">
          <el-select
            v-model="form.productName"
            placeholder="请选择"
            @change="bomchange"
          >
            <el-option v-for="item in productList" :value="item.productName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品编码:" prop="productCode">
          {{ this.form.productCode }}
        </el-form-item>
        <el-form-item label="bom编码:" prop="bomCode">
          <el-input v-model="form.bomCode" placeholder="请输入bom编码" />
        </el-form-item>
        <!-- <el-form-item label="物料id" prop="materialId">
          <el-input v-model="form.materialId" placeholder="请输入物料id" />
        </el-form-item>
        <el-form-item label="物料名称" prop="materialName">
          <el-input v-model="form.materialName" placeholder="请输入物料名称" />
        </el-form-item>
        <el-form-item label="物料数量" prop="materialNum">
          <el-input v-model="form.materialNum" placeholder="请输入物料数量" />
        </el-form-item>
        <el-form-item label="物料类型" prop="materialType">
          <el-input v-model="form.materialType" placeholder="请输入物料类型" />
        </el-form-item>
        <el-form-item label="备注" prop="note">
          <el-input v-model="form.note" placeholder="请输入备注" />
        </el-form-item> -->
        <el-form-item label="物料清单:" prop="productName"> </el-form-item>
        
        <!-- bom物料子表 -->
        <el-table :data="form.materials" style="width: 100%" max-height="250">
          <el-table-column type="index" width="50" label="序号">
          </el-table-column>
          <el-table-column align="center" label="物料名称" width="160">
            <template slot-scope="scope">
              <el-select
                v-model="form.materials[scope.$index].materialName"
                placeholder="请选择"
                style="width: 130px"
                @change="(option) => materialchange(option, scope.$index)"
              >
                <el-option
                  v-for="item in materialtable"
                  :value="item.materialName"
                >
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="物料编码"
            width="120"
            prop="materialCode"
          >
            <!-- {{ this.materialtable.materialName }} -->
          </el-table-column>
          <el-table-column align="center" label="数量" width="220">
            <template slot-scope="scope">
              <el-input-number
                v-model="form.materials[scope.$index].materialNum"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="120">
            <template slot-scope="scope">
              <el-button
                @click.native.prevent="deleteRow(scope.$index, form.materials)"
                type="text"
                size="small"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="mtradd">添加</el-button>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listBOM,
  getBOM,
  delBOM,
  addBOM,
  updateBOM,
  lookmaterial,
  newmaterial,
  addmaterial,
} from "@/api/mes/BOM";
import { listProduct, nullbomlist, getProduct } from "@/api/mes/product";

export default {
  name: "BOM",
  data() {
    return {
      value: "",
      mtrvalue: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // BOM管理表格数据
      BOMList: [],
      //产品管理表格数据
      productList: [],
      //产品详情
      tableProduct: "",
      //物料详情
      materialtable: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bomCode: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        bomCode: [
          { required: true, message: "bom编码不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    deleteRow(index, rows) {
      rows.splice(index, 1);
    },

    //添加物料
    mtradd(index) {
      if (index == undefined) {
        this.form.materials.push({
          materialName: null,
          materialType: null,
          materialNum: null,
          provider: null,
          materialCode: null,
        });
      } else {
        this.form.materials.splice(index + 1, 0, {
          materialName: null,
          materialType: null,
          materialNum: null,
          provider: null,
          materialCode: null,
        });
      }
    },
    /** 查询BOM管理列表 */
    getList() {
      this.loading = true;
      listBOM(this.queryParams).then((response) => {
        this.BOMList = response.rows;
        console.log(response.rows);
        this.total = response.total;
        this.loading = false;
      });

      //选择所有产品
      // listProduct(this.queryParams).then((response) => {
      //   this.productList = response.rows;
      //   this.total = response.total;
      //   this.loading = false;
      // });

      //选择未绑定bom的产品
      nullbomlist(this.queryParams).then((response) => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        productName: null,
        productCode: null,
        id: null,
        bomCode: null,
        materialId: null,
        materialName: null,
        materialNum: null,
        materialType: null,
        note: null,
        userId: null,
        createTime: null,
        materials: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加BOM管理";

      // 查看原料
      lookmaterial(this.queryParams).then((response) => {
        this.materialtable = response.rows;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getBOM(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改BOM管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.form);
      this.$refs["form"].validate((valid) => {
        if (valid) {
          console.log(this.form)
          if (this.form.id != null) {
            updateBOM(this.form).then((response) => {
              console.log(response);
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // 提交输入的信息
             addmaterial(this.form).then((response) => {
              console.log(response);
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除BOM管理编号为"' + ids + '"的数据项？')
        .then(function () {
          return delBOM(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "mes/BOM/export",
        {
          ...this.queryParams,
        },
        `BOM_${new Date().getTime()}.xlsx`
      );
    },
    /** 下拉框选择产品对应的编码*/
    bomchange(event) {
      this.form.productCode = this.productList.find(
        (item) => item.productName == event
      ).productCode;
      // console.log(this.form.productCode);
    },
    // 下拉框选择材料对应的编码
    materialchange(option, index) {
      let ss = this.materialtable.find(
        (item) => item.materialName == option
      ).materialCode;
      // console.log(option);
      // console.log(this.materialtable);
      this.form.materials[index].materialCode = ss;
    },
  },
};
</script>
